<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'/>
  <title>mapbox wind</title>
  <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no'/>
  <script src="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.js"></script>
  <link href="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.css" rel="stylesheet" />
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      background: #202020;
    }
  </style>
</head>
<body>
<div id='map'></div>
<!--<script src="https://cdn.jsdelivr.net/npm/@sakitam-gis/mapbox-wind@1.0.0-alpha.10/dist/mapbox-wind.js"></script>-->
<script src="../packages/mapbox-gl/dist/mapbox-wind.js"></script>
<script>
  mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA';
  const map = new mapboxgl.Map({
    container: 'map',
    style: {
      version: 8,
      sources: {
        carto: {
          type: 'raster',
          tiles: [
            '//a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
            '//b.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
            '//c.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
            '//d.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
          ],
          tileSize: 256,
          // minzoom: 1,
          // maxzoom: 18,
        },
      },
      layers: [
        {
          id: 'carto',
          type: 'raster',
          source: 'carto',
          // minzoom: 1,
          // maxzoom: 22,
          paint: {
            'raster-resampling': 'nearest',
            'raster-fade-duration': 0,
          },
        },
        {
          id: 'background',
          type: 'background',
          layout: {
            visibility: 'none',
          },
        },
      ],
    },
    center: [113.53450137499999, 34.44104525],
    zoom: 0
  });

  const color = {
    temp: [[203,[115,70,105,255]],
      [218,[202,172,195,255]],
      [233,[162,70,145,255]],
      [248,[143,89,169,255]],
      [258,[157,219,217,255]],
      [265,[106,191,181,255]],
      [269,[100,166,189,255]],
      [273.15,[93,133,198,255]],
      [274,[68,125,99,255]],
      [283,[128,147,24,255]],
      [294,[243,183,4,255]],
      [303,[232,83,25,255]],
      [320,[71,14,0,255]]],
  };

  map.on('load', function () {
    // fetch('https://sakitam-fdd.github.io/wind-layer/data/wind.json')
    fetch('./data/wind.json')
      .then(res => res.json())
      .then(data => {
        console.log(data);

        data = data.map((item, idx) => {
          item.header = Object.assign(item.header, {
            parameterCategory: 1,
            parameterNumber: idx === 0 ? 2 : 3,
          });
          return item;
        });

        const tempInterpolateColor = color.temp.reduce((result, item, key) => result.concat(item[0] - 273.15, 'rgba(' + item[1].join(',') + ')'), []);

        const fillLayer = new mapboxWind.ScalarFill('wind', {
          // "type": "jsonArray",
          // "data": data,
          "type": "image",
          "url": "./data/var_tmp.png",
          // 'extent': [
          //   [data[0]['header'].lo1, data[0]['header'].la1],
          //   [data[0]['header'].lo1, data[0]['header'].la2],
          //   [data[0]['header'].lo2, data[0]['header'].la1],
          //   [data[0]['header'].lo2, data[0]['header'].la2],
          // ],
          "extent": [
            [-180, 85.051129],
            [-180, -85.051129],
            [180, 85.051129],
            [180, -85.051129],
          ],
          "width": 1440,
          "height": 720,
          // "width": data[0]['header']['nx'],
          // "height": data[0]['header']['ny'] - 1,
          "min": -50.84996643066404,
          // "min": -63.83,
          "max": 42.25002441406252,
          // "max": 36.86,
        }, {
          wrapX: true,
          styleSpec: {
            'fill-color': [
              'interpolate',
              ['linear'],
              ['get', 'value'],
              ...tempInterpolateColor
            ],
            'opacity': [
              'interpolate',
              ['exponential', 0.5],
              ['zoom'],
              1,
              1,
              2,
              1
            ],
          },
          renderForm: 'r',
          widthSegments: 720,
          heightSegments: 360,
          // widthSegments: 1,
          // heightSegments: 1,
          // displayRange: [0, 80],
          mappingRange: [0, 5000000],
          // mappingRange: [0, 0],
        });

        map.addLayer(fillLayer);

        window.windLayer = new mapboxWind.WindLayer('wind', data, {
          windOptions: {
            // colorScale: (m) => {
            //   // console.log(m);
            //   return '#fff';
            // },
            // colorScale: [
            //   "rgb(36,104, 180)",
            //   "rgb(60,157, 194)",
            //   "rgb(128,205,193 )",
            //   "rgb(151,218,168 )",
            //   "rgb(198,231,181)",
            //   "rgb(238,247,217)",
            //   "rgb(255,238,159)",
            //   "rgb(252,217,125)",
            //   "rgb(255,182,100)",
            //   "rgb(252,150,75)",
            //   "rgb(250,112,52)",
            //   "rgb(245,64,32)",
            //   "rgb(237,45,28)",
            //   "rgb(220,24,32)",
            //   "rgb(180,0,35)"
            // ],
            // velocityScale: 1 / 20,
            // paths: 5000,
            frameRate: 16,
            maxAge: 60,
            globalAlpha: 0.9,
            velocityScale: 0.01,
            // paths: 10000,
            paths: 3782,
          },
        });

        console.log(map, window.windLayer);

        function draw(now) {
          var avg = 0;
          // for (var i = 0; i < bins; i++) {
          //   avg += dataArray[i];
          //   map.setPaintProperty(
          //     '3d-buildings-' + i,
          //     'fill-extrusion-height',
          //     10 + 4 * i + dataArray[i]
          //   );
          // }
          // avg /= bins;

          fillLayer.scalarFill.updateOptions({
            mappingRange: [0, Math.sin((now / 30 * Math.PI) / 90) * 5000000]
          });

          map.setBearing(now / 100);

          requestAnimationFrame(draw);
        }

        requestAnimationFrame(draw);

        // map.addLayer(window.windLayer);
        // window.windLayer.addTo(map);
      });
  });
</script>
</body>
</html>
